﻿/**
 * 分阶段加载本地数据缓存
 */
app.loading.set(0, () => cache.load());
app.loaded.set(0, () => {
    _site.drawMenu();
    _site.loadCommunitor();
});

/**
 * 本地数据缓存
 */
var cache = new (class _Cache_ {
    constructor() {
        this.parameters = [];
    }

    set(data) {
        this.parameters = data;
        this.root = this.parameters.get(x => x.key == "root", null, true);
        this.top = this.parameters.get(x => x.parent && x.parent.key === 'root');
        if ($.com.isArray(this.top)) {
            for (var index = 0; index < this.top.length; index++) {
                let element = this.top[index];
                this[element.key] = this.parameters.get(x => x.parent && x.parent.key == element.key);
            }
        }
    }

    load() {
        return this.loadUserInfo().then(() => this.loadParameters());
    }

    /**
     * 加载用户信息
     * @returns
     */
    loadUserInfo(force) {
        return Promise.resolve()
            .then(() => {
                let userInfo = localCache.global.get('userInfo');
                if (!userInfo || !!force) {
                    return axios.get('/api/account/getUserInfo')
                        .then(resp => resp.data)
                        .then(data => {
                            if (data && data.user && data.resources) {
                                localCache.global.set('userInfo', data);
                                _site.drawMenu();
                            }
                        });
                }
            });
    }

    /**
     * 加载基础数据
     * @returns
     */
    loadParameters(force) {
        return Promise.resolve()
            .then(() => {
                let parameters = localCache.global.get('parameters');
                if ($.com.isArray(parameters) && !force) {
                    this.set(parameters);
                } else {
                    return axios.get('/api/parameters?$select=id,index,key,value,text,parentId&$expand=parent($select=id,key)&$orderby=index')
                        .then(resp => resp.data)
                        .then(data => {
                            data = $.com.dataAdapter(data);
                            if ($.com.isArray(data)) {
                                localCache.global.set('parameters', data)
                                this.set(data);
                            }
                        });
                }
            });
    }
})();